package com.ks.app.admin.service.impl;

import java.util.List;
import javax.persistence.Query;
import org.springframework.stereotype.Service;
import com.ks.app.admin.hibernate.KsOperaterLog;
import com.ks.app.admin.service.KsoperatelogService;
import com.ks.app.admin.service.impl.BaseServiceImpl;
import com.ks.app.admin.util.Pager;


@Service("ksoperatelogService")
public class ksoperatelogServiceImpl extends BaseServiceImpl implements KsoperatelogService{
	
	/**
	 * 保存日志
	 */
	public void save(KsOperaterLog ksOperateLog) {
		em.persist(ksOperateLog);
	}

	
	@SuppressWarnings("unchecked")
	@Override
	/**
	 * 获取日志处理列表
	 * logtype 1 操作日志，2客户端日志
	 * status  2 已处理，  1 未处理
	 * opename 操作描述
	 * logtime 日志时间
	 */
	public List<KsOperaterLog> findKsOperaterLogList(String opename,String logtime,int logtype,
			int status, Pager pager) throws Exception{
		
		String sql  = " from KsOperaterLog where 1=1 ";
		String csql = " select count(*) from KsOperaterLog where 1=1";
		
		if (logtype != 0) {
			sql  = sql + "  and logtype="+logtype;
			csql = csql + "  and logtype="+logtype;
		}
		
		if(status != 0){
			sql  = sql +" and status="+status;
			csql = csql +" and status="+status;
		}
		
		if(!"".equals(opename)){
			sql  = sql +" and opename='"+opename+"'";
			csql = csql +" and opename='"+opename+"'";
		}
		
		if(!"".equals(logtime)){
			
			String[] ds = logtime.split("-");
			if(ds.length==3){
				sql  = sql +" and YEAR(logtime)="+ds[0]+" and MONTH(logtime)="+ds[1]+" and DAY(logtime)="+ds[2];
				csql = csql +" and YEAR(logtime)="+ds[0]+" and MONTH(logtime)="+ds[1]+" and DAY(logtime)="+ds[2];
			}
		}
		
		Query query = em.createQuery(sql);
		Query cquery = em.createQuery(csql);
	
		query.setMaxResults(pager.getCntOfPage());
		query.setFirstResult((pager.getCurPage() - 1) * pager.getCntOfPage());
		pager.setTotoalCnt(Integer.parseInt(String.valueOf(cquery.getSingleResult())));
		List<KsOperaterLog> list = query.getResultList();
		
		return list;
	
	}

	@Override
	/**
	 * 将已处理完的日志设为已处理
	 * logids 已处理的日志ID
	 */
	public void checkLog(String logids) {
		
		String hql = "update KsOperaterLog l set l.status =2 where l.id in ("+logids+")";
		em.createQuery(hql).executeUpdate();
		
	}
	
	/**
	 * 通过主键获取日志
	 */
	@Override
	public KsOperaterLog findLogById(long id) {
		
		return em.find(KsOperaterLog.class, id);
	
	}

}
